package cn._2dland.bots.jdo;

import java.util.List;

import javax.jdo.Query;

import cn._2dland.bots.jdo.models.Account;

@SuppressWarnings("unchecked")
public class AccountManager extends EntityManager{

	public AccountManager() {
		super();
	}
	
	/** 获取账户 */
	public Account getAccount(Long accoutnId) {
		return pm.getObjectById(Account.class, accoutnId);
	}
	public List<Account> getAccounts() {
		Query q = pm.newQuery(Account.class);
		List<Account> as = (List<Account>)q.execute();
		return as;
	}
	/** 添加一个账户 */
	public void addAccount(Account account) {
		pm.makePersistent(account);
	}
	/** 删除一个账户 */
	public void removeAccount(Long accoutnId) {
		Account a = pm.getObjectById(Account.class, accoutnId);
		pm.deletePersistent(a);
	}


	/**
	 * 创建账户
	 * @param username - 用户名
	 * @param password - 密码
	 * @return 创建后的账户ID
	 */
	public static long create(String username, String password){
		long acctId = -1;
		AccountManager am = new AccountManager();
		try {
			am.begin();
			Account acct = new Account(username, password);
			am.addAccount(acct);
			am.commit();

			acctId = acct.getID();
		}
		catch (Exception e) {
			am.rollback();
			e.printStackTrace();
			acctId = -1;
		}
		finally {
			am.close();
		}
		return acctId;
	}

	/**
	 * 删除账户
	 * @param id - 账户ID
	 * @return
	 */
	public static boolean remove(Long acctId) {
		boolean bOK = false;
		AccountManager am = new AccountManager();
		try {
			am.begin();
			am.removeAccount(acctId);
			am.commit();
			bOK = true;
		}
		catch (Exception e) {
			am.rollback();
			e.printStackTrace();
			bOK = false;
		}
		finally {
			am.close();
		}
		return bOK;
	}

	/** 设置账户状态 */
	public static void setStatus(Long acctId, int status) {
		AccountManager am = new AccountManager();
		try {
			am.begin();
			Account acct = am.getAccount(acctId);
			acct.setStatus(status);
			am.commit();
		}
		catch (Exception e) {
			am.rollback();
			e.printStackTrace();
		}
		finally {
			am.close();
		}
	}

	/** 更新账户最后活动时间 */
	public static void updateLastTime(Long acctId) {
		AccountManager am = new AccountManager();
		try {
			am.begin();
			Account acct = am.getAccount(acctId);
			acct.setLastTime(System.currentTimeMillis());
			am.commit();
		}
		catch (Exception e) {
			am.rollback();
			e.printStackTrace();
		}
		finally {
			am.close();
		}
	}
}